package utils.version6;

import service.version6.MyTransactional;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class TxInvocationHandler implements InvocationHandler {
    private TransactionManager transactionManager;
    private  Object target;

    public TxInvocationHandler(Object target,TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
        this.target = target;
    }

    private  boolean enableTx = false;
    private  void verify(Method method) {
        try {
            enableTx = target.getClass().getDeclaredMethod(method.getName(),method.getParameterTypes()).isAnnotationPresent(MyTransactional.class);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
    //method是代理方法，上面没有注解
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        verify(method);
        Object result = enableTx == true ? invokeWithTransaction(proxy, method, args) : invokeWithoutTransaction(proxy, method, args);
        return result;
    }
    private  Object invokeWithTransaction(Object proxy, Method method, Object[] args)throws Throwable {
        Object result = null;
        try {
            transactionManager.start();
            result = method.invoke(target, args);
            transactionManager.commit();
        }catch (RuntimeException e) {
            transactionManager.rollback();
            System.out.println(e.getMessage());
            throw e;
        }finally {
            transactionManager.getFactory().close();
        }
        return  result;
    }
    private  Object invokeWithoutTransaction(Object proxy, Method method, Object[] args)throws Throwable {
           return method.invoke(target, args);
    }
}
